package com.lovetransferjia.chatuidemo.jia.fragment;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lovetransferjia.chatuidemo.MyApplication;
import com.lovetransferjia.chatuidemo.R;
import com.lovetransferjia.chatuidemo.jia.utility.Communicator;
import com.lovetransferjia.chatuidemo.jia.utility.Utility;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.renn.rennsdk.RennClient;
import com.renn.rennsdk.RennClient.LoginListener;
import com.renn.rennsdk.RennExecutor.CallBack;
import com.renn.rennsdk.RennResponse;
import com.renn.rennsdk.exception.RennException;
import com.renn.rennsdk.param.PutFeedParam;

import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;

public class MyInfoFragment extends Fragment {
	TextView name,bio,school,major,active;
	ImageView imageView,bgImageView;
	Button button,sharetoR;
	String nameString="",genderString="",hobbyString="",bioString="",cityString="",schoolString="",majorString="",messageString="";
	String locationString="";
	ImageLoader imageLoader;
	Communicator communicator;
	RennClient rennClient=MyApplication.rennClient;
	private SmoothProgressBar mPocketBar;
	
 	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		imageLoader=MyApplication.imageLoader;
		communicator =(Communicator) getActivity();
		rennClient.setLoginListener(new LoginListener() {
			@Override
			public void onLoginSuccess() {
				// TODO Auto-generated method stub
				try {
					PutFeedParam param = new PutFeedParam();
					param.setTitle("快来加入校园偶遇");
					param.setMessage("这是一条新鲜事");
					param.setDescription("新鲜事Description");
					param.setTargetUrl("http://lovetransfer.duapp.com");
					rennClient.getRennService().sendAsynRequest(param, new CallBack() {
									@Override
									public void onSuccess(RennResponse response){
										// TODO Auto-generated method stub
										Toast.makeText(getActivity(), "成功", Toast.LENGTH_LONG).show();
									}
									@Override
									public void onFailed(String errorCode, String errorMessage) {
										// TODO Auto-generated method stub
										Toast.makeText(getActivity(), errorCode+errorMessage, Toast.LENGTH_LONG).show();
										Log.e("r",errorCode+errorMessage);
									}

								});
				} catch (RennException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			@Override
			public void onLoginCanceled() {
				// TODO Auto-generated method stub
			}

		});
		
		

 	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView;
		rootView = inflater.inflate(R.layout.jia_myprofile, container, false);
		mPocketBar=(SmoothProgressBar) rootView.findViewById(R.id.progressBar);
		mPocketBar.setVisibility(View.INVISIBLE);
		name=(TextView) rootView.findViewById(R.id.profile_name);
		/*gender=(TextView) rootView.findViewById(R.id.profile_gender);
		hobby=(TextView) rootView.findViewById(R.id.profile_hobby);*/
		bio=(TextView) rootView.findViewById(R.id.profile_bio);
		/*city=(TextView) rootView.findViewById(R.id.profile_city);*/
		school=(TextView) rootView.findViewById(R.id.profile_school);
		major=(TextView) rootView.findViewById(R.id.profile_major);
		active=(TextView) rootView.findViewById(R.id.active);
		imageView= (ImageView) rootView.findViewById(R.id.imageView1);
		bgImageView=(ImageView) rootView.findViewById(R.id.imageView2);
		sharetoR=(Button) rootView.findViewById(R.id.button2);
		LayoutParams para;  
		para = bgImageView.getLayoutParams();  
		if(true)
		{
			DisplayMetrics dm = new DisplayMetrics();
			getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
			// 屏幕宽度
			int screenWidth = dm.widthPixels;
			MyApplication.screenWidth=screenWidth;
			// 屏幕高度
			int screenHeight = dm.heightPixels;
			Rect frame = new Rect();  
			getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
			int statusBarHeight = frame.top;
			final float scale = getActivity().getResources().getDisplayMetrics().density;
			para.height =(int) (screenHeight-(98)*scale-statusBarHeight);    
			para.width=screenWidth;
			bgImageView.setLayoutParams(para);
		}
		
		
		boolean getinfo=false;
		if(MyApplication.my_name!=null){
			name.setText(MyApplication.my_name);
		}else{ getinfo=true;}
		if(MyApplication.my_school!=null){
			school.setText(MyApplication.my_school);
		}else{ getinfo=true;}
		if(MyApplication.my_major!=null){
			major.setText(MyApplication.my_major);
		}else{ getinfo=true;}
		if(MyApplication.my_bio!=null){
			bio.setText(MyApplication.my_bio);
		}
		if(MyApplication.my_img!=null){
			imageLoader.displayImage(MyApplication.my_img, imageView);
		}else{ getinfo=true;}
		if(MyApplication.my_active!=null){
			active.setText(MyApplication.my_active);
		}
		
			new GetInfo().execute(MyApplication.id);
		
		
		active.setOnClickListener( new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(getActivity() != null)
				Toast.makeText(getActivity(), "活跃度越高，匹配到的Ta也越活跃哦！", Toast.LENGTH_LONG).show();
			}
		});
		
		sharetoR.setOnClickListener( new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//rennClient.login(getActivity());
				dialog();
			}
		});
		
		
		button=(Button) rootView.findViewById(R.id.button1);
		if(MyApplication.headimage!=null)
		{
			imageLoader.displayImage(MyApplication.headimage, imageView);
		}
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				communicator.respond("go to modify");
			}
		
		});
		
		return rootView;
	}
	
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
	}
	public void renrenshare(){
		PutFeedParam param = new PutFeedParam();
		param.setTitle("快来加入校园偶遇");
		param.setMessage("发现一个交友利器：");
		param.setDescription("记得《爱情呼叫转移》里徐郎的手机吗，加入校园偶遇，每天都会遇到有缘人，基于活跃度和个人信息匹配，一对一结识，再也不用担心找不到对象了");
		param.setTargetUrl("http://lovetransfer.duapp.com");
		try {
			rennClient.getRennService().sendAsynRequest(param, new CallBack() {
							@Override
							public void onSuccess(RennResponse response){
								// TODO Auto-generated method stub
								new Renren().execute();
							}
							@Override
							public void onFailed(String errorCode, String errorMessage) {
								// TODO Auto-generated method stub
								Toast.makeText(getActivity(), "分享失败："+errorCode+errorMessage, Toast.LENGTH_LONG).show();
								Log.e("r",errorCode+errorMessage);
							}

						});
		} catch (RennException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	protected void dialog() {
		  AlertDialog.Builder builder = new Builder(getActivity());
		  builder.setMessage("记得《爱情呼叫转移》里徐郎的手机吗，加入校园偶遇，每天都会遇到有缘人，基于活跃度和个人信息匹配，一对一结识，再也不用担心找不到对象了");

		  builder.setTitle("快来加入校园偶遇");

		  builder.setPositiveButton("确认分享", new DialogInterface.OnClickListener() {

		   @Override
		   public void onClick(DialogInterface dialog, int which) {
		   
		    renrenshare();
		    dialog.dismiss();
		   }
		  });

		  builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

		   @Override
		   public void onClick(DialogInterface dialog, int which) {
		    dialog.dismiss();
		   }
		  });

		  builder.create().show();
		 }


	public class GetInfo extends AsyncTask<String, Void, Boolean>{
		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			mPocketBar.setVisibility(View.INVISIBLE);
			if(result==true){
				name.setText(nameString);
				//city.setText(cityString);
				bio.setText(bioString);
				//hobby.setText(hobbyString);
				school.setText(schoolString);
				major.setText(majorString);
				if(genderString.equals("0"))
					name.append("(女)");
				else {
					name.append("(男)");
				}
				active.setText(activeString);
				imageLoader.displayImage(locationString, imageView);
				MyApplication.headimage=locationString;
				MyApplication.my_img=locationString;
				MyApplication.my_name=nameString;
				MyApplication.my_bio=bioString;
				MyApplication.my_school=schoolString;
				MyApplication.my_major=majorString;
				MyApplication.my_active=activeString;
			}
		}
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			mPocketBar.setVisibility(View.VISIBLE);
		}
		String urlString=MyApplication.baseUrl+"user_info/info/"+"0"+"/0"+MyApplication.postfix;
		String failString="",activeString="";
		@Override
		protected Boolean doInBackground(String... args) {
			urlString=MyApplication.baseUrl+"user_info/info/"+args[0]+"/0"+MyApplication.postfix;
			try {
				JSONObject jsonObject = Utility.GETObject(urlString, failString);
				nameString=jsonObject.getString("name");
				genderString=jsonObject.getString("gender");
				cityString=jsonObject.getString("city");
				schoolString=jsonObject.getString("school");
				majorString=jsonObject.getString("major");
				hobbyString=jsonObject.getString("hobby");
				bioString=jsonObject.getString("profile");
				locationString=jsonObject.getString("headimage");
				activeString=jsonObject.getString("active");
				return true;
			}catch (Exception e)
			{
				Log.w("Getinfo",e.toString());
				failString="网络连接出错";
			}
			return false;
		}
		
	}
	
	public class Renren extends AsyncTask<String, Void, Boolean>{
		String urlString=MyApplication.baseUrl+"user_info/renrenshare"+MyApplication.postfix;
		String failString="",statusString="";
		@Override
		protected Boolean doInBackground(String... params) {
			// TODO Auto-generated method stub
			try{
			JSONObject jsonObject=Utility.GETObject(urlString, failString);
			statusString=jsonObject.getString("status");
			return true;
			}catch(Exception e){
				failString=e.toString();
			}
			return false;
		}
		@Override
		protected void onPostExecute(Boolean result) {
			if(result==true){
				Toast.makeText(getActivity(), "分享成功,每天首次分享可获得活跃度奖励", Toast.LENGTH_LONG).show();
			}else{
				Toast.makeText(getActivity(), "服务器连接失败", Toast.LENGTH_SHORT).show();
			}
		}
	
	}

}

